package utils

import (
	"encoding/binary"
	"regexp"

	"gitee.com/les49/esgo/encoding/base58"

	"golang.org/x/crypto/bcrypt"
)

/*
检测密码是否符合规范 需要至少8位 并且需要包含数字和字母
*/
//密码强度必须为字⺟⼤⼩写+数字+符号，9位以上
func GetPasswordLever(ps string) int32 {
	level := int32(0)
	if len(ps) < 8 {
		return 0
	}
	num := `[0-9]{1}`
	a_z := `[a-z]{1}`
	A_Z := `[A-Z]{1}`
	symbol := `[!@#~$%^&*()+|_]{1}`

	if b, err := regexp.MatchString(num, ps); b && err == nil {
		level++
	}
	if b, err := regexp.MatchString(a_z, ps); b && err == nil {
		level++
	}
	if b, err := regexp.MatchString(A_Z, ps); b && err == nil {
		level++
	}
	if b, err := regexp.MatchString(symbol, ps); b && err == nil {
		level++
	}
	return level
}

func GeneratePassword(uid uint32, pwd string) string {
	buf := make([]byte, binary.MaxVarintLen32)
	binary.BigEndian.PutUint32(buf, uid)
	uuid := base58.Encode(buf)
	md5 := MD5V([]byte(uuid + pwd + "e+to7y4C"))
	hash, _ := bcrypt.GenerateFromPassword([]byte(md5), bcrypt.DefaultCost)
	encodePwd := string(hash)
	return encodePwd
}

func ComparePassword(uid uint32, loginPwd, dbPwd string) bool {
	buf := make([]byte, binary.MaxVarintLen32)
	binary.BigEndian.PutUint32(buf, uid)
	uuid := base58.Encode(buf)
	md5 := MD5V([]byte(uuid + loginPwd + "e+to7y4C"))
	err := bcrypt.CompareHashAndPassword([]byte(dbPwd), []byte(md5))
	if err == nil {
		return true
	}
	return false
}
